package control;

import java.util.ArrayList;

import control.server.Request;
import control.server.Response;
import model.entity.Agent;
import model.entity.Task;

public class PathFinder {
	
	private Agent agent;
	private Task task;
	private Response res;
	
	private ArrayList<Integer> movesToTake = new ArrayList<Integer>(); // valid values: 1 up, 2 right, 3 down, 4 left
	
	private int[] agentMoved;
	private int[] movedAgentDistances;
	
	

	public PathFinder(Response r) {
		this.res = r;
		
	}
	
	/**
	 * 
	 * @param a Az ügynök aminek az útvonalát kell tervezni
	 * @param t Egy munka ahova el kell jutni az ügynökkel
	 * @return Az ügynök által bejárandó útvonal, int[] : values: 0 up, 1 right, 2 down, 3 left, az út hossza a tömb mérete
	 */
	
	public ArrayList<Integer> FindPath(Agent a, Task t) {
		this.agent = a;
		this.task = t;
		
		while(agent.getCoordinate() != task.getCoordinate()) {
			agentMoved[0] = agent.getCoordinate()-res.getMapsize();
			agentMoved[1] = agent.getCoordinate()+1;
			agentMoved[2] = agent.getCoordinate()+res.getMapsize();
			agentMoved[3] = agent.getCoordinate()-1;
			
			int minimalDist = Integer.MAX_VALUE;
			int moveDir=0;
			
			for(int i = 0; i <4; i++) {
				
				Integer[] roadblocks = res.getRoadblocks().get(agent.getCoordinate());
				
				for(int j=0;j<roadblocks.length;i++) {
					if(agentMoved[i]==roadblocks[j]) {
						agentMoved[i] = -1; //érvénytelen lépés lenne útzár miatt
					}
				}
			}
			
			for(int i = 0; i < 4; i++) {
				if(agentMoved[i]!=-1) {
					movedAgentDistances[i] = heuristicDistance(agentMoved[i]);
				}else {
					movedAgentDistances[i] = Integer.MAX_VALUE;
				}
			}
			
			for(int i = 0; i < 4; i++) {
				if(movedAgentDistances[i]<minimalDist) {
					minimalDist=movedAgentDistances[i];
					moveDir=i;
				}
			}
			
			agent.setCoordinate(agentMoved[moveDir]);
			movesToTake.add(moveDir);
			
		}

		for (int i : movesToTake) {
			System.out.println(i);
		}
			
		
		
		return movesToTake;
	}
	
	private int heuristicDistance(int movedAgentPos) {
		double dist=0;
		int mapsize = res.getMapsize();
		int taskcoord = task.getCoordinate();
		int agentcoord = movedAgentPos;
		int tx = taskcoord%res.getMapsize();  //task mod mapsize
		if(tx==0) tx = mapsize;
		int ax = agentcoord%res.getMapsize(); //agent mod mapsize
		if(ax==0) ax = mapsize;
		dist = Math.sqrt((tx-ax)*(tx-ax)+((taskcoord/mapsize)-(agentcoord/mapsize))*((taskcoord/mapsize)-(agentcoord/mapsize)));
		
		return (int)Math.round(dist);
		
	}
	
	
	
}
